﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MadeInPortugal.Class;
using MadeInPortugal;
using System.Collections;
using System.Data;

namespace MadeInPortugalWebApplication.WebControl
{
    public partial class PropertiesWC : System.Web.UI.UserControl
    {
        int UserId = 0;
        String UserType;
        bool[] rowChanged;
        bool[] rowDeleted;

        bool[] TagrowChanged;
        bool[] TagrowDeleted;

        bool[] TyperowChanged;
        bool[] TyperowDeleted;
        GeneralProperties _srv = new GeneralProperties();
        ProductType ProdType = new ProductType();
        Tag ProdTag = new Tag();

        ArrayList propertiesSource = new ArrayList();
        ArrayList TypeSource = new ArrayList();
        ArrayList TagSource = new ArrayList();
        DataTable dtPages;

        public int CurrentPage
        {
            get { return int.Parse(hfPageNumber.Value); }
            set { hfPageNumber.Value = value.ToString(); ; }
        }

        public int PageSize
        {
            get;
            set;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckUser();
            base.OnInit(e);

            SetFeedBack("", Messages.FeedBackType.hide);
            PageSize = 10;
            if (!IsPostBack)
            {
                fillTypeDropdown();
                FillTagDropDown();
                GetProperties();
                FillPropertiesTermsPages();
                FillTypePages();
                FillTagsPages();
            }
            else
            {
                propertiesSource = (ArrayList)Session["userlist"];
                TagSource = (ArrayList)Session["taglist"];
                TypeSource = (ArrayList)Session["typelist"];
            }

            DtPages = (DataTable)ViewState["pages"];


        }

        #region Dropdown
        private void CheckUser()
        {
            if (Session["UserType"] == null)
                Response.Redirect("index.aspx");
            if ((Session["UserId"] == null) || ((string)Session["UserId"] == "0"))
                Response.Redirect("index.aspx");
            UserType = Session["UserType"].ToString();
            int.TryParse(Session["UserId"].ToString(), out UserId);
        }

        protected void fillTypeDropdown()
        {
            ddlType.Items.Clear();
            ProductType type = new ProductType();
            ProductType[] typeList = type.GetAllType();
            foreach (ProductType item in typeList)
            {
                ddlType.Items.Add(new ListItem(item.Type, item.ID.ToString()));
            }

        }

        private void FillTagDropDown()
        {
            ddlTag.Items.Clear();
            Tag type = new Tag();
            Tag[] typeList = type.GetTagByTypeId(int.Parse(ddlType.SelectedValue));
            foreach (Tag item in typeList)
            {
                ddlTag.Items.Add(new ListItem(item.TagName, item.ID.ToString()));
            }
            //GetProperties();

        }

        protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
        {
            FillTagDropDown();
            propertiesSource.Clear();
            TagSource.Clear();
            TypeSource.Clear();
            TypeSource.Add(ProdType.Get(int.Parse(ddlType.SelectedValue)));
            TagSource.AddRange(ProdTag.GetTagByTypeId(int.Parse(ddlType.SelectedValue)));
            if (ddlTag.SelectedItem != null)
                propertiesSource.AddRange(_srv.GetProperties(int.Parse(ddlTag.SelectedValue)));
        }
        protected void ddlTag_SelectedIndexChanged(object sender, EventArgs e)
        {
            propertiesSource.Clear();
            TagSource.Clear();

            TagSource.AddRange(ProdTag.GetTagByTypeId(int.Parse(ddlType.SelectedValue)));
            if (ddlTag.SelectedItem !=null)
                propertiesSource.AddRange(_srv.GetProperties(int.Parse(ddlTag.SelectedValue)));
        }

        #endregion

        public DataTable DtPages
        {
            get
            {
                if (dtPages == null)
                {
                    dtPages = new DataTable();
                    dtPages.Columns.Add("Class");
                    dtPages.Columns.Add("PageNumber");
                }
                return dtPages;
            }
            set
            {
                if (value != null)
                    dtPages = value;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            int totalRows = propertiesGridView.Rows.Count;
            rowChanged = new bool[totalRows];
            rowDeleted = new bool[totalRows];

            int totalTagRows = TagGridview.Rows.Count;
            TagrowChanged = new bool[totalTagRows];
            TagrowDeleted = new bool[totalTagRows];

            int totalTypeRows = TypeGridview.Rows.Count;
            TyperowChanged = new bool[totalTypeRows];
            TyperowDeleted = new bool[totalTypeRows];
            BuildPagination();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (Page.IsPostBack)
            {
                PropertiesChanges();
                TypeChanges();
                TagChanges();
                //fillTypeDropdown();
                //FillTagDropDown();
            }

            FillPropertiesTermsPages();
            FillTypePages();
            FillTagsPages();

            BuildPagination();

            ViewState["pages"] = DtPages;
            Session["userlist"] = propertiesSource;
            Session["taglist"] = TagSource;
            Session["typelist"] = TypeSource;
        }

        private void PropertiesChanges()
        {
            try
            {
                int totalRows = propertiesGridView.Rows.Count;
                for (int r = 0; r < totalRows; r++)
                {
                    if (rowChanged[r])
                    {
                        GridViewRow thisGridViewRow = propertiesGridView.Rows[r];
                        Label lbPk = (Label)thisGridViewRow.FindControl("lbNumber");
                        TextBox tbxTerm = (TextBox)thisGridViewRow.FindControl("tbxTerm");
                        int pk = 0;
                        if (int.TryParse(lbPk.Text, out pk))
                        {
                            GeneralProperties updated = _srv.Update(new GeneralProperties() { ID = pk, PropertyName = tbxTerm.Text.Trim() });

                            if (updated != null)
                            {
                                SetFeedBack(string.Format("O termo '{0}' foi actualizado com sucesso.", updated.PropertyName), Messages.FeedBackType.success);
                            }
                            else
                            {
                                SetFeedBack(string.Format("Ocorreu um erro ao actualizar o termo '{0}'.", updated.PropertyName), Messages.FeedBackType.error);
                            }
                        }
                        GetProperties();
                        // Only one row afected by postback
                        break;
                    }
                    if (rowDeleted[r])
                    {
                        GridViewRow thisGridViewRow = propertiesGridView.Rows[r];
                        Label lbPk = (Label)thisGridViewRow.FindControl("lbNumber");
                        Label lbTerm = (Label)thisGridViewRow.FindControl("lbTerm");
                        int pk = 0;
                        if (int.TryParse(lbPk.Text, out pk))
                        {
                            GeneralProperties updated = _srv.Delete(new GeneralProperties() { ID = pk, PropertyName = lbTerm.Text.Trim() });

                            if (updated != null)
                            {
                                SetFeedBack(string.Format("O termo '{0}' foi eliminado com sucesso.", updated.PropertyName), Messages.FeedBackType.success);
                            }
                            else
                            {
                                SetFeedBack(string.Format("Ocorreu um erro ao eliminar o termo '{0}'.", updated.PropertyName), Messages.FeedBackType.error);
                            }
                        }
                        GetProperties();
                        // Only one row afected by postback
                        break;
                    }
                }
            }
            catch (Exception)
            {

            }
        }


        private void TypeChanges()
        {
            try
            {
                int totalRows = TypeGridview.Rows.Count;
                for (int r = 0; r < totalRows; r++)
                {

                    if (TyperowChanged[r])
                    {
                        GridViewRow thisGridViewRow = TypeGridview.Rows[r];
                        Label lbPk = (Label)thisGridViewRow.FindControl("lbTypeNumber");
                        TextBox tbxTypeTerm = (TextBox)thisGridViewRow.FindControl("tbxTypeTerm");
                        int pk = 0;
                        if (int.TryParse(lbPk.Text, out pk))
                        {
                            ProductType updated = ProdType.Update(new ProductType() { ID = pk, Type = tbxTypeTerm.Text.Trim() });

                            if (updated != null)
                            {
                                SetFeedBack(string.Format("A Propriedade '{0}' foi actualizada com sucesso.", updated.Type), Messages.FeedBackType.success);
                            }
                            else
                            {
                                SetFeedBack(string.Format("Ocorreu um erro ao actualizar a Propriedade '{0}'.", updated.Type), Messages.FeedBackType.error);
                            }
                        }
                        GetProperties();
                        // Only one row afected by postback
                        break;
                    }
                    if (TyperowDeleted[r])
                    {
                        GridViewRow thisGridViewRow = TypeGridview.Rows[r];
                        Label lbPk = (Label)thisGridViewRow.FindControl("lbTypeNumber");
                        Label lbTerm = (Label)thisGridViewRow.FindControl("lbTypeTerm");
                        int pk = 0;
                        if (int.TryParse(lbPk.Text, out pk))
                        {
                            int ret = ProdType.Delete(pk);

                            if (ret != 0)
                            {
                                SetFeedBack(string.Format("O Type '{0}' foi eliminado com sucesso.", lbTerm), Messages.FeedBackType.success);
                            }
                            else
                            {
                                SetFeedBack(string.Format("Ocorreu um erro ao eliminar o Type '{0}'.", lbTerm), Messages.FeedBackType.error);
                            }
                        }
                        GetProperties();
                        // Only one row afected by postback
                        break;
                    }

                }
            }
            catch (Exception)
            {
            }
        }

        private void TagChanges()
        {
            try
            {
                int totalRows = TagGridview.Rows.Count;
                for (int r = 0; r < totalRows; r++)
                {

                    if (TagrowChanged[r])
                    {
                        GridViewRow thisGridViewRow = TagGridview.Rows[r];
                        Label lbPk = (Label)thisGridViewRow.FindControl("lbTagNumber");
                        TextBox tbxTagTerm = (TextBox)thisGridViewRow.FindControl("tbxTagTerm");
                        int pk = 0;
                        if (int.TryParse(lbPk.Text, out pk))
                        {
                            Tag updated = ProdTag.Update(new Tag() { ID = pk, TagName = tbxTagTerm.Text.Trim() });

                            if (updated != null)
                            {
                                SetFeedBack(string.Format("A Tag '{0}' foi actualizado com sucesso.", updated.TagName), Messages.FeedBackType.success);
                            }
                            else
                            {
                                SetFeedBack(string.Format("Ocorreu um erro ao actualizar a Tag '{0}'.", updated.TagName), Messages.FeedBackType.error);
                            }
                        }
                        GetProperties();
                        // Only one row afected by postback
                        break;
                    }
                    if (TagrowDeleted[r])
                    {
                        GridViewRow thisGridViewRow = TagGridview.Rows[r];
                        Label lbPk = (Label)thisGridViewRow.FindControl("lbTagNumber");
                        Label lbTerm = (Label)thisGridViewRow.FindControl("lbTagTerm");
                        int pk = 0;
                        if (int.TryParse(lbPk.Text, out pk))
                        {
                            int ret = ProdTag.Delete(pk);

                            if (ret != 0)
                            {
                                SetFeedBack(string.Format("A Tag '{0}' foi eliminado com sucesso.", lbTerm.Text), Messages.FeedBackType.success);
                            }
                            else
                            {
                                SetFeedBack(string.Format("Ocorreu um erro ao eliminar a Tag '{0}'.", lbTerm.Text), Messages.FeedBackType.error);
                            }
                        }
                        GetProperties();
                        // Only one row afected by postback
                        break;
                    }

                }
            }
            catch (Exception)
            {
            }
        }
        protected void GridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("deleteBlacklist"))
            {
                int row;
                if (int.TryParse(e.CommandArgument.ToString(), out row))
                    rowDeleted[row] = true;
            }
            if (e.CommandName.Equals("saveBlacklist"))
            {
                int row;
                if (int.TryParse(e.CommandArgument.ToString(), out row))
                    rowChanged[row] = true;
            }
        }

        protected void TagGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("deleteBlacklist"))
            {
                int row;
                if (int.TryParse(e.CommandArgument.ToString(), out row))
                    TagrowDeleted[row] = true;
            }
            if (e.CommandName.Equals("saveBlacklist"))
            {
                int row;
                if (int.TryParse(e.CommandArgument.ToString(), out row))
                    TagrowChanged[row] = true;
            }
        }

        protected void TypeGridView_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("deleteBlacklist"))
            {
                int row;
                if (int.TryParse(e.CommandArgument.ToString(), out row))
                    TyperowDeleted[row] = true;
            }
            if (e.CommandName.Equals("saveBlacklist"))
            {
                int row;
                if (int.TryParse(e.CommandArgument.ToString(), out row))
                    TyperowChanged[row] = true;
            }
        }

        protected void SaveNewTerm_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbxNewTerm.Text))
            {
                GeneralProperties inserted = _srv.Insert(new GeneralProperties() { PropertyName = tbxNewTerm.Text.Trim() }, int.Parse(ddlTag.SelectedItem.Value));

                if (inserted != null)
                {
                    SetFeedBack(string.Format("O termo '{0}' foi adicionado com sucesso.", inserted.PropertyName), Messages.FeedBackType.success);
                    tbxNewTerm.Text = "";
                }
                else
                {
                    SetFeedBack(string.Format("Ocorreu um erro ao adicionar o termo '{0}'.", inserted.PropertyName), Messages.FeedBackType.error);
                }
                GetProperties();
            }
            else
            {
                SetFeedBack("Não é possível inserir termos vazios.", Messages.FeedBackType.info);
            }

        }

        protected void RepeaterChangePage_Command(object sender, RepeaterCommandEventArgs e)
        {
            if (e.CommandName.Equals("goPage"))
            {
                int pageSelected = 1;
                if (int.TryParse(e.CommandArgument.ToString(), out pageSelected))
                {
                    CurrentPage = pageSelected;
                }
            }
        }

        private void BuildPagination()
        {
            DtPages.Clear();
            if (propertiesSource.Count > PageSize)
            {
                int intermediateCount = 0;
                while (intermediateCount < propertiesSource.Count)
                {
                    int pageNr = intermediateCount / PageSize + 1;

                    DataRow dr = DtPages.NewRow();
                    dr["Class"] = (pageNr == CurrentPage ? "current" : string.Empty);
                    dr["PageNumber"] = pageNr;
                    DtPages.Rows.Add(dr);

                    intermediateCount += PageSize;
                }

                paginationList.DataSource = DtPages;
                paginationList.DataBind();
            }
        }

        private void GetProperties()
        {
            propertiesSource.Clear();
            TypeSource.Clear();
            TagSource.Clear();
            TypeSource.Add(ProdType.Get(int.Parse(ddlType.SelectedValue)));
            if (ddlTag.SelectedItem != null)
                if (ddlTag.SelectedItem.Text != "-1")
                {
                    propertiesSource.AddRange(_srv.GetProperties(int.Parse(ddlTag.SelectedItem.Value)));
                    TagSource.AddRange(ProdTag.GetTagByTypeId(int.Parse(ddlType.SelectedValue)));
                }
        }


        private void FillPropertiesTermsPages()
        {
            int intermCount = ((CurrentPage) * PageSize > propertiesSource.Count) ? (propertiesSource.Count - (CurrentPage - 1) * PageSize) : PageSize;
            propertiesGridView.DataSource = propertiesSource.GetRange((CurrentPage - 1) * PageSize, intermCount);
            propertiesGridView.DataBind();
        }
        private void FillTypePages()
        {
            int intermCount = ((CurrentPage) * PageSize > TypeSource.Count) ? (TypeSource.Count - (CurrentPage - 1) * PageSize) : PageSize;
            TypeGridview.DataSource = TypeSource.GetRange((CurrentPage - 1) * PageSize, intermCount);
            TypeGridview.DataBind();
        }

        private void FillTagsPages()
        {
            int intermCount = ((CurrentPage) * PageSize > TagSource.Count) ? (TagSource.Count - (CurrentPage - 1) * PageSize) : PageSize;
            TagGridview.DataSource = TagSource.GetRange((CurrentPage - 1) * PageSize, intermCount);
            TagGridview.DataBind();
        }


        private void SetFeedBack(string htmlMessage, Messages.FeedBackType fType)
        {
            feedbackPanel.InnerHtml = htmlMessage;
            feedbackPanel.Attributes.Add("class", fType.ToString());
        }


        protected void lbAddTipo_Click(object sender, EventArgs e)
        {
            try
            {
                ProductType type = new ProductType();
                type.Insert(tbxTipo.Text);
                fillTypeDropdown();
                ddlType.SelectedItem.Text = tbxTipo.Text;
                FillTagDropDown();

                //FillPropertiesTermsPages();
                SetFeedBack(string.Format("A Tag '{0}' foi adicionada com sucesso.", tbxTipo.Text), Messages.FeedBackType.success);
                tbxTipo.Text = "";
            }
            catch (Exception)
            {

                SetFeedBack(string.Format("Ocorreu um erro ao actualizar o termo '{0}'.", tbxTipo.Text), Messages.FeedBackType.error);
            }
        }

        protected void lblAddTag_Click(object sender, EventArgs e)
        {
            try
            {
                Tag newtag = new Tag();
                newtag = newtag.Insert(tbxTag.Text);
                TagType insertTagType = new TagType();
                insertTagType.Insert(newtag.ID, int.Parse(ddlType.SelectedItem.Value));
                fillTypeDropdown();
                ddlType.SelectedItem.Text = tbxTipo.Text;
                FillTagDropDown();

                //FillPropertiesTermsPages();
                SetFeedBack(string.Format("A Tag '{0}' foi adicionada com sucesso.", tbxTag.Text), Messages.FeedBackType.success);
                tbxTag.Text = "";
            }
            catch (Exception)
            {

                SetFeedBack(string.Format("Ocorreu um erro ao actualizar o termo '{0}'.", tbxTag.Text), Messages.FeedBackType.error);
            }
        }
    }
}
